
//  用第三方的mp3编码
// 尝试推流
// !!! 5 修改这里的url 后缀必须为 /
// var BASE_URL = "wss://xxxx/huohuaqi/webchart/"  // 线上
var BASE_URL = ""   // ws://localhost:9966/huohuaqi/webchart/    // 本地测试
BASE_URL = window.location.href;
BASE_URL = "ws" + BASE_URL.substring(4, BASE_URL.lastIndexOf("/") + 1);
BASE_URL
console.log("BASE_URL = " + BASE_URL);

var fps = 20;
var HEIGHT = 360;
var WIDTH = document.body.clientWidth;  // 500



let username = document.getElementById("username");
let list = document.getElementById("list");
let btn_conn = document.getElementById("conn");
let btn_changename = document.getElementById("changename");

function randomString(len) {
　　len = len || 16;
　　var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
　　var maxPos = $chars.length;
　　var pwd = '';
　　for (i = 0; i < len; i++) {
　　　　pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
　　}
　　return pwd;
}

var recorder = new MP3Recorder({
    debug:true,
    bitRate: 64,
    funOk: function () {
        console.log('初始化MP3Recorder成功');
    },
    funCancel: function (msg) {
        console.log(msg);
        recorder = null;
        alert("没有麦克风权限！只能听别人声音")
    }
});

function BLOCK (data, next) {
    this.data = data;
    this.next = next;
}
function FIFO(MAX_N){
    this.MAX_N = MAX_N;
    this.list = null;
    this.head = null;
    this.tail = null;
    this.num = 0;
    this.put = function(block){
        if(this.num == this.MAX_N){
            this.head = this.head.next;
            this.tail.next=block;
            this.tail = block;
        }else{
            if(this.head == null){
                this.head = block;
                this.tail = block;
                this.num = 1;
            }else{
                this.tail.next=block;
                this.tail = block;
                this.num ++;
            }
        }
    }
    this.get = function(){
        if(this.num == 0)
            return null;
        else{
            let a = this.head;
            this.head = this.head.next;
            this.num --;
            return a; 
        }
    }
}


var ws = null;  // websocket
var heartJump = null; // 心跳
let user = {}; // user {id,name}

// websocket以及语音处理部分
var FF = new FIFO(3);  // 录音队列
// 查看上次是否有 localstorage
user = localStorage.getItem("user");
if(user){
    user = JSON.parse(user);
    username.value = user.name;
}else{
    user = {}
    user.id = randomString(16);
    user.name = user.id;
    localStorage.setItem("user", JSON.stringify(user));
}
// 与服务器建立websocket
if(ws != null){
    ws.close();
    ws=null;
}
ws = new WebSocket(BASE_URL +  user.id);
ws.binaryData = "arraybuffer";

ws.onopen = function() {
    console.log('握手成功');
    ws.send(JSON.stringify({
        op: "rename",
        name: user.name,
    }));
    if(heartJump != null){
        clearInterval(heartJump);
        heartJump = null;
    }
    heartJump = setInterval(()=>{
        console.log("ping 心跳");
        ws.send(JSON.stringify({
            op: "ping"
        }));
    }, 1000*45);  // 45s心跳
};
ws.onerror = function(err){
    console.log(err);
}
ws.onclose = function(err){
    // alert(err);
    alert("已断开服务, 请重新连接");
    ws = null;
}

ws.onmessage = function(e) {
    // console.log("e.data:" + e.data);
    receive(e.data);
};
let luyin_d = null; // 录音线程
let send_d = null;  // 发送线程
function start_record(){
        // 录音线程
        recorder.start();
        if(luyin_d) clearInterval(luyin_d);
        luyin_d = setInterval( ()=>{
            // recorder.stop();
            recorder.getMp3Blob((blob) => {
                FF.put(new BLOCK(blob, null));
                recorder.continue();
            }, (err)=>{
                console.log("获取MP3 blob 出错");
            } )
        }, 50);  // 时间越小，越清晰

        // 发送线程
        if(send_d) clearInterval(send_d);
        send_d = setInterval( ()=>{
            let aa = FF.get();
            if(aa)
                ws.send(aa.data);
        }, 50); // 时间越小，越清晰
        btn_conn.innerText = "断开";
}
btn_conn.onclick = function() {   // 拨号
    if(btn_conn.innerText == "连接"){
        var selects= document.getElementsByName('select');
        let select = null;
        for (var i = 0; i < selects.length; i++) {
            if (selects[i].checked == true) { //如果选中，下面的alert就会弹出选中的值
                select = selects[i];
            }
        }
        if(select == null) {alert("未选择对象"); return;}
        let re_conn_id = select.id;
        ws.send(JSON.stringify({
            op: "conn",
            want: re_conn_id,  // 想要连接的对方ID
        }));
        // 连接成功之后，在回调里面开启录音
    }else{
        ws.send(JSON.stringify({
            op: "disconn"
        }));
        recorder.stop();
        if(luyin_d) clearInterval(luyin_d);
        if(send_d) clearInterval(send_d);
        btn_conn.innerText = "连接";
    }
}
btn_changename.onclick=function(){ // 重新命名
    user.name = username.value;
    ws.send(JSON.stringify({
        op: "rename",
        name: username.value
    }));
    localStorage.setItem("user", JSON.stringify({
        id: user.id,
        name: user.name
    }))
}

var AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext(); //实例化AudioContext对象
function receive(e) {
    try {
        // 接收二进制音频
        if(e.size ){
            console.log("recv blob, size is :"+ e.size);
            //将Blob 对象转换成 ArrayBuffer
            var reader = new FileReader();
            reader.readAsArrayBuffer(e);
            reader.onload = function (e) {
                audioContext.decodeAudioData(reader.result, function(buffer) {//解码成pcm流
                    var audioBufferSouceNode = audioContext.createBufferSource();
                    audioBufferSouceNode.buffer = buffer;
                    audioBufferSouceNode.connect(audioContext.destination);
                    audioBufferSouceNode.start(0);
                }, function(e) {
                    console.log("failed to decode the file");
                });
            }
        }else{
            // 接收文本
            console.log("recv txt: "+e);
            if(e == "pong"){
                console.log("心跳");
                return;
            }
            let obj = JSON.parse(e);
            if(obj.op == "list"){  // 更新最新在线的列表
                list.innerHTML = "";
                for(let i=0; i<obj.ids.length; i++){
                    let li = document.createElement("li");
                    let radio=document.createElement("input");
                    let label = document.createElement("label");
                    radio.type = "radio";
                    radio.name = "select";  // name要统一
                    radio.id = obj.ids[i];
                    let isMe = obj.ids[i] == user.id ? "[自己]" : ""; 
                    label.innerText = obj.names[i] + isMe;
                    label.appendChild(radio);
                    li.appendChild(label);
                    list.appendChild(li);
                }
            }else if(obj.op == "conn_resp"){  // 连接成功的话
                if(obj.res == 'succ')
                    start_record();
                else if(obj.res == "fail")
                    alert("连接失败，对方正在通话");
                else if(obj.res == "self")
                    alert("连接失败，不能自连");
            }else if(obj.op == "disconn"){  // 被对方宣布挂断电话
                recorder.stop();
                if(luyin_d) clearInterval(luyin_d);
                if(send_d) clearInterval(send_d);
                btn_conn.innerText = "连接";
            }else if(obj.op == 'ask'){  // 询问是否接收对方连接
                let radio = document.getElementById(obj.uid);
                if(radio) radio.checked = true;
                start_record();
            }
        }
    } catch (error) {
        console.log(error);
    }
}